import { domUtils } from '../utils/domUtils';
import { LogService } from '../services/logService';

export class FloatingToolbar {
    constructor(options = {}) {
        this.toolbar = null;
        this.options = options;
        this.handlers = {};
        this.selectedText = '';
        this.logger = new LogService('FloatingToolbar');
    }

    show(position, selectedText) {
        this.logger.debug('Showing toolbar', { position, selectedText });
        this.remove();
        this.selectedText = selectedText;
        this.toolbar = this.createToolbar(position);
        document.body.appendChild(this.toolbar);
    }

    remove() {
        this.logger.debug('Removing toolbar');
        if (this.toolbar && this.toolbar.parentNode) {
            
            this.toolbar.parentNode.removeChild(this.toolbar);
            this.toolbar = null;
        }
    }

    on(event, handler) {
        this.handlers[event] = handler;
    }

    createToolbar(position) {
        this.logger.debug('Creating toolbar', { position });
        const toolbar = domUtils.createElementWithStyles('div', {
            position: 'fixed',
            zIndex: '10000',
            background: '#FFFFFF',
            border: '1px solid #E2E8F0',
            boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
            borderRadius: '6px',
            padding: '6px 8px',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '6px',
            minHeight: '32px',
            backdropFilter: 'blur(8px)',
        });
        
        toolbar.id = 'floating-toolbar';
        
        // 设置工具栏样式和位置
        this.setToolbarPosition(toolbar, position);
        
        // 添加工具按钮
        toolbar.appendChild(this.createToolIcon());
        toolbar.appendChild(this.createDivider());
        toolbar.appendChild(this.createTranslateButton());
        toolbar.appendChild(this.createSummarizeButton());
        toolbar.appendChild(this.createExplainButton());

        return toolbar;
    }

    setToolbarPosition(toolbar, position) {
        this.logger.debug('Setting position', { position });
        const padding = 10;
        let { left, top } = position;
        
        // 延迟获取工具栏尺寸，确保DOM已渲染
        requestAnimationFrame(() => {
            const rect = toolbar.getBoundingClientRect();
            const maxX = window.innerWidth - rect.width - padding;
            const maxY = window.innerHeight - rect.height - padding;

            left = Math.min(maxX, Math.max(padding, left + padding));
            top = Math.min(maxY, Math.max(padding, top - padding));

            Object.assign(toolbar.style, {
                left: `${left}px`,
                top: `${top}px`
            });
        });
    }

    createToolIcon() {
        const icon = domUtils.createElementWithStyles('div', {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '0 2px'
        });

        const img = document.createElement('img');
        img.src = chrome.runtime.getURL('images/icon16.png');
        img.width = 16;
        img.height = 16;
        icon.appendChild(img);
        
        return icon;
    }

    createDivider() {
        return domUtils.createElementWithStyles('div', {
            width: '1px',
            height: '16px',
            background: '#E2E8F0',
            margin: '0 2px'
        });
    }

    createButton(text, icon, handler) {
        const button = domUtils.createElementWithStyles('button', {
            display: 'inline-flex',
            alignItems: 'center',
            gap: '4px',
            padding: '4px 8px',
            border: 'none',
            borderRadius: '4px',
            background: 'transparent',
            color: '#475569',
            fontSize: '13px',
            fontWeight: '500',
            cursor: 'pointer',
            transition: 'all 0.2s',
            whiteSpace: 'nowrap',
            userSelect: 'none'
        });

        button.innerHTML = icon + text;
        button.onclick = handler;
        
        return button;
    }

    createTranslateButton() {
        return this.createButton(
            '翻译', 
            `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0 0 14.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04z" 
                    fill="currentColor"/>
            </svg>`,
            () => this.handlers['translate']?.(this.selectedText)
        );
    }

    createSummarizeButton() {
        return this.createButton(
            '总结', 
            `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M14 17h-7M17 13H7M17 9H7M17 5H7" 
                    stroke="currentColor" 
                    stroke-width="2" 
                    stroke-linecap="round"/>
            </svg>`,
            () => this.handlers['summarize']?.(this.selectedText)
        );
    }

    createExplainButton() {
        return this.createButton(
            '解释', 
            `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01" 
                    stroke="currentColor" 
                    stroke-width="2" 
                    stroke-linecap="round" 
                    stroke-linejoin="round"/>
            </svg>`,
            () => this.handlers['explain']?.(this.selectedText)
        );
    }
} 